const express = require("express")

const app = express()

const MAO = require('multer-aliyun-oss');
//阿里云oss操作对象
const OSS = require('ali-oss');

const multer = require('multer')

app.use(require('cors')()) //消除跨域

// 阿里云上传文件后改一下后缀名
//Promise化
function updateName(req, res) {
    return new Promise((resolve, reject) => {
        const client = new OSS({
            region: '',
            accessKeyId: '',
            accessKeySecret: '',
            bucket: '',
        })
        const suffix = req.files[0].filename.slice(-4)
        client.copy(`${Date.now()}${suffix}`, `${req.files[0].filename}`)
            .then(r => {
                // req.url = r.res.requestUrls
                console.log('拷贝成功');
                client
                    // 删除srcobject.txt。
                    .delete(`${req.files[0].filename}`)
                    .then(r => console.log("删除成功"))
                    .catch(e => console.log("删除失败"));
                resolve(r)
            })
            .catch(e => console.log('拷贝失败', e));
    })


};


app.post('/upload', multer({
    //设置文件存储路径
    // dest: "upload"
    storage: MAO({
        //这里自行看阿里云文档.
        config: {
            region: 'oss-cn-guangzhou',
            accessKeyId: 'LTAI5tNTeDjuwr5ChoaNGw74',
            accessKeySecret: 'BwmtxT2oZqMOeeSVBAvlcmHSMVCqmx',
            bucket: 'gurr',
        },
    })
}).array('file', 100), function (req, res, next) {  //这里100表示最大支持的文件上传数目  file需要和前端一致

    let files = req.files;
    if (files.length === 0) {
        res.render("error", { message: "上传文件不能为空！" });
        return
    } else {
        updateName(req, res).then(r => {
            req.files[0].url = r.res.requestUrls[0]
            res.send(req.files)
        })
    }
});

app.listen(4003, () => {
    console.log("http://127.0.0.1:4003");
})